/* ===========================================================
 * docsify sw.js
 * ===========================================================
 * Copyright 2016 @huxpro
 * Licensed under Apache 2.0
 * Register service worker.
 * ========================================================== */

const RUNTIME = 'docsify'
const HOSTNAME_WHITELIST = [
  self.location.hostname,
  'fonts.gstatic.com',
  'fonts.googleapis.com',
  'cdn.jsdelivr.net',
  'cdn.staticfile.net',
  'cdnjs.cloudflare.com'
]

// 预缓存关键资源（安装阶段）
const PRECACHE_URLS = [
  '/_sidebar.md',
  '/_navbar.md',
  '/index.html',
  '/favicon.ico'
];

// The Util Function to hack URLs of intercepted requests
const getFixedUrl = (req) => {
    var now = Date.now()
    var url = new URL(req.url)

    // 1. fixed http URL
    // Just keep syncing with location.protocol
    // fetch(httpURL) belongs to active mixed content.
    // And fetch(httpRequest) is not supported yet.
    url.protocol = self.location.protocol

    // 2. add query for caching-busting.
    // Github Pages served with Cache-Control: max-age=600
    // max-age on mutable content is error-prone, with SW life of bugs can even extend.
    // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
    // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
    if (url.hostname === self.location.hostname) {
        url.search += (url.search ? '&' : '?') + 'cache-bust=' + now
    }
    return url.href
}

// 从HTML中提取资源URL
const extractResourceUrls = (html, baseUrl) => {
    const urls = [];

    // 提取CSS
    const cssRegex = /<link[^>]+rel=["']stylesheet["'][^>]+href=["']([^"']+)["']/gi;
    let match;
    while ((match = cssRegex.exec(html)) !== null) {
        try {
            urls.push(new URL(match[1], baseUrl).href);
        } catch (e) {}
    }

    // 提取JS
    const jsRegex = /<script[^>]+src=["']([^"']+)["']/gi;
    while ((match = jsRegex.exec(html)) !== null) {
        try {
            urls.push(new URL(match[1], baseUrl).href);
        } catch (e) {}
    }

    // 提取图片
    const imgRegex = /<img[^>]+src=["']([^"']+)["']/gi;
    while ((match = imgRegex.exec(html)) !== null) {
        try {
            urls.push(new URL(match[1], baseUrl).href);
        } catch (e) {}
    }

    return urls;
};

/**
 *  @Lifecycle Install
 *  预缓存关键资源
 */
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(RUNTIME)
        .then(cache => cache.addAll(PRECACHE_URLS.filter(url => {
            try {
                return HOSTNAME_WHITELIST.includes(new URL(url, self.location).hostname);
            } catch (e) {
                return false;
            }
        })))
        .then(() => self.skipWaiting())
    );
});

/**
 *  @Lifecycle Activate
 *  New one activated when old isnt being used.
 *
 *  waitUntil(): activating ====> activated
 */
self.addEventListener('activate', event => {
    event.waitUntil(self.clients.claim());
});

/**
 *  @Functional Fetch
 *  All network requests are being intercepted here.
 *
 *  void respondWith(Promise<Response> r)
 */
self.addEventListener('fetch', event => {

    if (event.request.url.includes('/logout')) {
        return; // 跳过缓存
    }

    // Skip some of cross-origin requests, like those for Google Analytics.
    if (HOSTNAME_WHITELIST.includes(new URL(event.request.url).hostname)) {
        // Stale-while-revalidate
        // similar to HTTP's stale-while-revalidate:   https://www.mnot.net/blog/2007/12/12/stale  
        // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1  
        const cached = caches.match(event.request);
        const fixedUrl = getFixedUrl(event.request);
        const fetched = fetch(fixedUrl, {
            cache: 'no-store'
        });
        const fetchedCopy = fetched.then(resp => resp.clone());

        // Call respondWith() with whatever we get first.
        // If the fetch fails (e.g disconnected), wait for the cache.
        // If there’s nothing in cache, wait for the fetch.
        // If neither yields a response, return offline pages.
        event.respondWith(
            Promise.race([fetched.catch(_ => cached), cached])
            .then(resp => resp || fetched)
            .catch(_ => {
                /* eat any errors */ })
        );

        // Update the cache with the version we fetched (only for ok status)
        // 并且主动缓存HTML中引用的其他资源
        event.waitUntil(
            (async () => {
                try {
                    const [response, cache] = await Promise.all([
            fetchedCopy,
            caches.open(RUNTIME)
          ]);

                    // 常规缓存更新
                    if (response.ok) {
                        await cache.put(event.request, response.clone());
                    }

                    // 如果是HTML文档，提取并缓存页面中引用的资源
                    const contentType = response.headers.get('Content-Type') || '';
                    if (contentType.includes('text/html')) {
                        const html = await response.text();
                        const baseUrl = event.request.url;
                        const resourceUrls = extractResourceUrls(html, baseUrl);

                        // 过滤出HOSTNAME_WHITELIST中的资源并缓存
                        for (const url of resourceUrls) {
                            try {
                                const hostname = new URL(url).hostname;
                                if (HOSTNAME_WHITELIST.includes(hostname)) {
                                    // 检查是否已缓存
                                    const isCached = await caches.match(url);
                                    if (!isCached) {
                                        const resourceResponse = await fetch(url, {
                                            cache: 'no-store'
                                        });
                                        if (resourceResponse.ok) {
                                            await cache.put(url, resourceResponse);
                                        }
                                    }
                                }
                            } catch (e) {
                                // 忽略无效URL
                            }
                        }
                    }
                } catch (e) {
                    // 忽略错误
                }
            })()
        );
    }
});